<template>
  <div class="r-upload">
    <el-upload
      :ref="refName"
      drag
      size="mini"
      :action="fileConfig.action"
      multiple
      :file-list="fileList"
      :http-request="httpRequest"
      :before-remove="beforeRemove"
      :before-upload="beforeUpload"
      :on-remove="onRemove"
      :on-preview="download"
      :accept="'.' + fileType"
      v-bind="attrsList"
    >
      <i class="el-icon-upload" />
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <div slot="tip" class="el-upload__tip">只能上传{{ fileType }}文件</div>
    </el-upload>
    <el-dialog title="请输入版本号" :visible="dialogVisible">
      <el-input v-model="remark" placeholder="请输入版本号" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="onCancleVersion">取 消</el-button>
        <el-button type="primary" @click="onSubmitVersion">
          确 定
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Message } from 'element-ui'
import {
  uploadFile,
  getFileList,
  uploadConfig,
  deleteFileById,
  getImgUrl,
  downloadFileByUrl
} from '@/api/file'

// // 获取文件后缀名
// const getExtension = fileName => {
//   // 文件扩展名的正则表达式
//   var patternFileExtension = /\.([0-9a-z]+)(?:[\?#]|$)/i
//   // 获得文件扩展名
//   var fileExtension = fileName.match(patternFileExtension)
//   return fileExtension[0] || ''
// }

export default {
  props: {
    value: {
      type: [String, Number],
      default: ''
    },
    fileType: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      fileConfig: uploadConfig(),
      fileList: [],
      imgLimit: 9,
      attachLimit: 3,

      dialogVisible: false,
      uploadPromis: {},
      remark: ''
    }
  },
  computed: {
    refName() {
      return 'r-upload-ref' + this.fileType
    },
    uploadDom() {
      return this.$refs[this.refName]
    },
    attrsList() {
      return {}
    }
  },
  mounted() {
    // 初始化时 获取列表
    this.loadFileList(this.value)
  },
  methods: {
    // 自定义请求
    async httpRequest(req) {
      const { retData, success, msg } = await uploadFile(
        req.file,
        this.value,
        this.remark
      )
      if (!success) {
        // 上传失败时,  删除上传文件
        this.uploadDom.uploadFiles.splice(
          this.uploadDom.uploadFiles.length - 1,
          1
        )
        Message.warning(msg)
        this.fileList = this.uploadDom.uploadFiles
        return
      }
      const [firstRet] = retData || []
      const { businessId } = firstRet || {}
      if (businessId) {
        const uploadFiles = [].concat(this.uploadDom.uploadFiles)
        const newFile = uploadFiles.pop()

        Object.assign(newFile, {
          id: firstRet.id,
          url: getImgUrl(firstRet.id),
          name: `版本号: ${firstRet.remark}; 文件名：${firstRet.originalName}`
        })
        this.fileList = [newFile].concat(uploadFiles)
      }
      this.remark = ''
    },
    // 上传前
    beforeUpload(file) {
      this.dialogVisible = true
      return new Promise((resolve, reject) => {
        this.uploadPromis = {
          resolve,
          reject
        }
      })
    },
    onSubmitVersion() {
      if (!this.remark) {
        Message.warning('请输入版本号！')
        return
      }
      this.uploadPromis.resolve()
      this.dialogVisible = false
    },
    onCancleVersion() {
      this.dialogVisible = false
      // 上传失败，所以把缓存删除
      this.uploadDom.uploadFiles.pop()
      this.uploadPromis.reject()
      this.remark = ''
    },
    // 加载文件list
    async loadFileList(busiId) {
      if (!busiId || this.fileList.length) {
        return
      }
      const { retData } = await getFileList(busiId) //

      this.fileList = (retData || []).map(fItem =>
        Object.assign(fItem, {
          name: `版本号: ${fItem.remark}; 文件名：${fItem.originalName}`,
          url: getImgUrl(fItem.id)
        })
      )
    },

    // 删除-前 file, fileList
    async beforeRemove(file) {
      const { success, msg } = await deleteFileById(file.id)
      if (!success) {
        Message.warning(msg)
        return Promise.reject()
      }
      return Promise.resolve()
    },
    onRemove(file, fileList) {
      this.fileList = fileList
    },

    // 下载附件
    download(file) {
      downloadFileByUrl(file.id)
    }
  }
}
</script>

<style lang="scss" scoped></style>
